package com.campus.secondhand.controller;

import java.security.Principal;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.campus.secondhand.common.Result;
import com.campus.secondhand.entity.User;
import com.campus.secondhand.model.dto.LoginDTO;
import com.campus.secondhand.model.dto.RegisterDTO;
import com.campus.secondhand.model.dto.UpdatePasswordDTO;
import com.campus.secondhand.model.dto.UserInfoDTO;
import com.campus.secondhand.model.dto.ResetPasswordDTO;
import com.campus.secondhand.model.dto.VerificationCodeDTO;
import com.campus.secondhand.model.vo.ProductListVO;
import com.campus.secondhand.model.vo.PurchaseRequestVO;
import com.campus.secondhand.model.vo.UserInfoVO;
import com.campus.secondhand.model.vo.UserLoginVO;
import com.campus.secondhand.service.ProductService;
import com.campus.secondhand.service.PurchaseRequestService;
import com.campus.secondhand.service.UserService;
import com.campus.secondhand.service.VerificationCodeService;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
@Slf4j
public class UserController {

    private final UserService userService;
    private final VerificationCodeService verificationCodeService;
    private final ProductService productService;
    private final PurchaseRequestService purchaseRequestService;

    /**
     * 用户登录
     * 
     * @param loginDTO 登录信息
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result<UserLoginVO> login(@Validated @RequestBody LoginDTO loginDTO) {
        return userService.login(loginDTO);
    }

    /**
     * 用户注销
     * 
     * @return 注销结果
     */
    @PostMapping("/logout")
    @PreAuthorize("isAuthenticated()")
    public Result<Void> logout() {
        // 客户端删除token即可
        return Result.success(null, "已注销");
    }

    /**
     * 用户注册
     * 
     * @param registerDTO 注册信息
     * @return 注册结果
     */
    @PostMapping("/register")
    public Result<User> register(@Validated @RequestBody RegisterDTO registerDTO) {
        return userService.register(registerDTO);
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("/info")
    @PreAuthorize("isAuthenticated()")
    public Result<UserInfoVO> getUserInfo(@RequestParam Long userId) {
        return userService.getUserInfo(userId);
    }

    /**
     * 获取个人详细信息
     *
     * @param principal 当前登录用户
     * @return 用户详细信息
     */
    @GetMapping("/profile")
    @PreAuthorize("isAuthenticated()")
    public Result<UserInfoVO> getUserProfile(Principal principal) {
        Result<User> userResult = userService.getByUsername(principal.getName());
        if (userResult.getCode() != 200) {
            return Result.error(userResult.getCode(), userResult.getMessage());
        }
        return userService.getUserInfo(userResult.getData().getId());
    }

    /**
     * 更新用户信息
     * 
     * @param principal   当前登录用户
     * @param userInfoDTO 用户信息
     * @return 更新结果
     */
    @PutMapping("/info")
    @PreAuthorize("isAuthenticated()")
    public Result<Void> updateUserInfo(Principal principal, @ModelAttribute UserInfoDTO userInfoDTO) {
        Result<User> userResult = userService.getByUsername(principal.getName());
        if (userResult.getCode() != 200) {
            return Result.error(userResult.getCode(), userResult.getMessage());
        }
        return userService.updateUserInfo(userResult.getData().getId(), userInfoDTO);
    }

    /**
     * 修改密码（已登录用户）
     * 需要验证旧密码
     * 
     * @param principal         当前登录用户
     * @param updatePasswordDTO 密码信息
     * @return 处理结果
     */
    @PutMapping("/password")
    @PreAuthorize("isAuthenticated()")
    public Result<Void> updatePassword(Principal principal,
            @Validated @RequestBody UpdatePasswordDTO updatePasswordDTO) {
        Result<User> userResult = userService.getByUsername(principal.getName());
        if (userResult.getCode() != 200) {
            return Result.error(userResult.getCode(), userResult.getMessage());
        }
        return userService.updatePassword(userResult.getData().getId(), updatePasswordDTO);
    }

    /**
     * 重置密码（忘记密码）
     * 需要手机验证码验证
     * 
     * @param resetPasswordDTO 重置密码信息
     * @return 处理结果
     */
    @PostMapping("/reset-password")
    public Result<Void> resetPassword(@Validated @RequestBody ResetPasswordDTO resetPasswordDTO) {
        return userService.resetPassword(resetPasswordDTO);
    }

    /**
     * 发送手机验证码
     * 
     * @param verificationCodeDTO 验证码请求，包含手机号和验证码类型(register|reset)
     * @return 处理结果
     */
    @PostMapping("/send-code")
    public Result<Void> sendVerificationCode(@Validated @RequestBody VerificationCodeDTO verificationCodeDTO) {
        // 检查验证码类型是否有效
        String type = verificationCodeDTO.getType();
        if (type != null && !type.equals("register") && !type.equals("reset")) {
            return Result.error(400, "无效的验证码类型，只支持register或reset");
        }

        return verificationCodeService.generateAndSendCode(verificationCodeDTO.getPhone(),
                verificationCodeDTO.getType());
    }

    /**
     * 检查登录状态
     * 
     * @param principal 当前登录用户
     * @return 登录状态
     */
    @GetMapping("/check-status")
    public Result<UserInfoVO> checkLoginStatus(Principal principal) {
        // 如果principal为null，表示未登录
        if (principal == null) {
            return Result.error(401, "未登录");
        }

        // 获取用户信息
        Result<User> userResult = userService.getByUsername(principal.getName());
        if (userResult.getCode() != 200) {
            return Result.error(userResult.getCode(), userResult.getMessage());
        }

        // 返回用户信息
        return userService.getUserInfo(userResult.getData().getId());
    }

    /**
     * 获取用户商品列表
     * 
     * @param userId   用户ID
     * @param page     页码，默认为1
     * @param pageSize 每页数量，默认为10
     * @return 用户商品列表
     */
    @GetMapping("/products")
    public Result<Page<ProductListVO>> getUserProducts(
            @RequestParam(required = true) Long userId,
            @RequestParam(required = false, defaultValue = "1") int page,
            @RequestParam(required = false, defaultValue = "10") int pageSize) {

        // 由于前端页码从1开始，而Spring分页从0开始，需要减1
        Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Direction.DESC, "createdAt"));
        // 状态筛选由前端处理
        return productService.getUserProducts(userId, pageable);
    }

    /**
     * 获取用户求购列表
     * 
     * @param userId   用户ID
     * @param page     页码，默认为1
     * @param pageSize 每页数量，默认为10
     * @return 用户求购列表
     */
    @GetMapping("/requests")
    public Result<Page<PurchaseRequestVO>> getUserRequests(
            @RequestParam(required = true) Long userId,
            @RequestParam(required = false, defaultValue = "1") int page,
            @RequestParam(required = false, defaultValue = "10") int pageSize) {

        // 由于前端页码从1开始，而Spring分页从0开始，需要减1
        Pageable pageable = PageRequest.of(page - 1, pageSize, Sort.by(Sort.Direction.DESC, "createdAt"));
        return purchaseRequestService.getUserRequests(userId, pageable);
    }
}